<template>
  <div class="player">
    <audio src="/public/music.mp3" controls @timeupdate="handleTimeUpdate"></audio>
  </div>

  <div class="container">
    <div class="lyric-container">
      <ul :style="trans">
        <li v-for="(lyric, index) in lyricList" :key="index" :class="{ active: currentIndex === index }">
          {{ lyric.text }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
// 当前歌词及激活歌词系数
const currentLyric = ref('')
const currentIndex = ref(0)
// 歌词列表
const lyricList = ref([])
// li高度
const liHeight = ref(30)

// 获得播放歌词及对应系数
const handleTimeUpdate = (e) => {
  const currentTime = e.target.currentTime
  lyricList.value.forEach((item, index) => {
    if (currentTime >= item.time) {
      currentLyric.value = item.text
      currentIndex.value = index
    }
  })
}

// 歌词url
const url = 'http://project.x-zd.net:3001/apis/songword'
// 获取歌词
onMounted(async () => {
  // 发送请求
  const res = await fetch(url).then((res) => res.json())
  lyricList.value = formatLyric(res.data)
})

// 歌词格式转换
function formatLyric(lyric) {
  // 格式化歌词
  const arr = lyric.split('\n')
  // 设置歌词时间
  const result = []
  // 对每行歌词的时间进行处理
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i].trim()
    // 过滤空行
    if (item) {
      // 分开时间和文本
      const [timeStamp, text] = item.split(']')
      // 分割分钟和秒
      const [minute, secondAndMilli] = timeStamp.slice(1).split(':')
      const [second, millisecond] = secondAndMilli.split('.')
      const time = parseInt(minute) * 60 + parseInt(second) + parseFloat(millisecond) / 100
      result.push({
        time,
        text
      })
    }
  }
  return result
}

// 歌词居中显示
// 计算偏移量，使当前激活的 li 居中显示
const trans = computed(() => {
  // 前6个li不滚动
  if (currentIndex.value < 7) {
    return {}
  } else {
    // 第7个开始滚动,并令ul移动对应的li高度
    const transY = -liHeight.value * (currentIndex.value - 6) + 'px'
    return `transform: translateY(${transY});`
  }
})
</script>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: black;
  height: 100%;
}

.player {
  margin: 0 auto;
  text-align: center;
}

.lyric-container {
  text-align: center;
  height: 420px;
  overflow: hidden;
  margin-top: 20px;
  font-size: 16px;
  color: #666;

  ul {
    transition: 0.5s;
    list-style: none;

    li {
      height: 30px;
      line-height: 30px;
      transition: 0.2s;

      &.active {
        color: #eee;
        font-size: 24px;
      }
    }
  }
}
</style>
